using System;
using System.IO;

namespace BSDS.Core.Data.Local
{
    public class DataFormatRecognizer
    {
        public DataFormat Recognize(string filename)
        {
            string firstLine;

            using(var reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
            {
                firstLine = reader.ReadLine();

                // The line which reads "Bing Spatial Data Services, 1.0, <entity type name>" is optional for the BSDS tool. Skip it if found.
                var BingSDSheader = firstLine.Split(',');
                if (BingSDSheader[0].Trim() == "Bing Spatial Data Services")
                    firstLine = reader.ReadLine();
            }

            if(firstLine == null)
            {
                throw new ArgumentException("No data in file: " + filename);
            }

            if(firstLine.Contains("<?xml version=\"1.0\" standalone=\"yes\"?>"))
            {
                return DataFormat.Xml;
            }

            if(firstLine.Contains("|"))
            {
                return DataFormat.Pipe;
            }

            if(firstLine.Contains("\t"))
            {
                return DataFormat.Tab;
            }

            if(firstLine.Contains(","))
            {
                return DataFormat.Comma;
            }

            throw new ArgumentException("Unrecognized file format of input file: " + filename);
        }
    }
}